package com.game.sdk.handle;

import akka.actor.ActorRef;
import com.coment.cfg.luban.GiftCfg;
import com.coment.cfg.luban.Tables;
import com.coment.cfg.luban.constant.CurrencyType;
import com.coment.cfg.luban.gift.GiftWorthCfg;
import com.coment.dto.ApiNotify;
import com.coment.enums.PushType;
import com.coment.message.account.ReceiveInfo;
import com.coment.po.UserInfo;
import com.game.dao.user.UserPlayInfoDao;
import com.game.framework.ActorManager;
import com.game.logic.core.system.ServerInfoService;
import com.game.logic.fighting.skill.skill.GiftSkillsEventHandler;
import com.game.logic.gift.GiftActor;
import com.game.logic.items.account.UserAccountActor;
import com.game.logic.ranking.GameRakingService;
import com.game.sdk.ApiNotifyEvent;
import com.xs.build.server.websocket.channel.ClientManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/// 礼物处理
@Slf4j
@Service
public class GiftChain {
    private static final long ONE_DAY_MILLIS = 86400000L;
    @Resource
    private GameRakingService rakingService;
    @Resource
    private UserPlayInfoDao userPlayInfoDao;
    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Async
    @EventListener(classes = ApiNotifyEvent.class)
    public void handle(ApiNotifyEvent event) {
        ApiNotify body = event.getBody();
        try {
            if (body.getPushType().equals(PushType.gift.getValue())) {

                GiftCfg giftCfg = Tables.cfg.get_tbgiftcfg().data();
                this.recordContributionValue(body, giftCfg);
                this.convertToCardPackage(body, giftCfg);
                GiftSkillsEventHandler.GiftSkillsEvent giftSkillsEvent = new GiftSkillsEventHandler.GiftSkillsEvent(
                        this,
                        body.getAnchorInfoId(),
                        body.getUserInfo().getId(),
                        body.getGiftId(),
                        body.getGiftCount()
                );
                this.eventPublisher.publishEvent(giftSkillsEvent);
                ActorManager.getActor(GiftActor.class, body.getGiftId()).tell(body, ActorRef.noSender());
            }
        } catch (Exception e) {
            log.error("GiftChain handle error", e);
        }


    }

    /// 转换为卡包
    @Async
    public void convertToCardPackage(ApiNotify body, GiftCfg giftCfg) {
        UserInfo userInfo = body.getUserInfo();
        int userInfoId = userInfo.getId();
        float giftTotalPrice = (float) body.getGiftTotalPrice();
        float value1 = giftCfg.value1;
        float obtainNum = giftTotalPrice * value1;

        log.debug("礼物{}名称{}单价{} 数量{} 总价{} 转化为卡包{}",
                body.getGiftId(),
                body.getGiftName(),
                body.getGiftUnitPrice(),
                body.getGiftCount(),
                body.getGiftTotalPrice(),
                obtainNum
        );

        ReceiveInfo info = new ReceiveInfo(
                userInfoId,
                CurrencyType.card,
                obtainNum,
                "获得卡包"
        );
        ReceiveInfo receiveInfo = ActorManager.ask(UserAccountActor.class, info, userInfoId);
        ClientManager.sendMessageToClient(userInfoId, receiveInfo);
    }


    /// 创纪录的贡献价值
    @Async
    protected void recordContributionValue(ApiNotify body, GiftCfg giftCfg) {
        long serviceOpeningTime = ServerInfoService.serverInfo.getServiceOpeningTime();

        GiftWorthCfg worthCfg = Tables.cfg.get_tbgiftworthcfg().get(body.getGiftId());
        if (worthCfg == null) {
            return;
        }
        if (worthCfg.price <= 0) {
            return;
        }
        int total = worthCfg.price * body.getGiftCount();


        float value2 = giftCfg.value2;

        //
        float value3 = giftCfg.value3;
        float value4 = giftCfg.value4;
        int day = (int) ((System.currentTimeMillis() - serviceOpeningTime) / ONE_DAY_MILLIS);
        float mValue = value3 + value4 * (float) day;


        float averageRevenuePerUser = total * value2 * mValue;
        int giftCount = body.getGiftCount();
        log.info("礼物{}名称{}单价{} 数量{} 总价{} 贡献价值{}",
                body.getGiftId(),
                body.getGiftName(),
                body.getGiftUnitPrice(),
                giftCount,
                body.getGiftTotalPrice(),
                averageRevenuePerUser
        );

        UserInfo userInfo = body.getUserInfo();
        Integer userInfoId = userInfo.getId();
        Integer lastAnchorInfoId = userPlayInfoDao.findByUserInfoIdOrCreate(userInfoId).getRecentlyPlayedAnchorInfoId();
        this.rakingService.addContribution(lastAnchorInfoId, userInfoId, averageRevenuePerUser);
    }
}
